<template>
  <div>
    <el-button-group>
      <el-button type="primary" size="small" @click="visible=true;handleType='add'">+ 新增部门</el-button>
      <el-button plain icon="el-icon-refresh-right" size="small" @click="refresh">刷新</el-button>
      <el-button plain icon="el-icon-delete" size="small" @click="batchDel">删除</el-button>
    </el-button-group>
    <el-table
      class="mt-10"
      :data="list"
      row-key="id"
      border
      size="small"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      ref="organTable"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="organName" label="部门名称"></el-table-column>
      <el-table-column prop="description" label="部门描述"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" plain @click="update(scope.row)">编辑</el-button>
          <el-button type="primary" size="mini" plain @click="addsub(scope.row)">添加下级部门</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增 修改部门-->
    <el-dialog
      :title="handleType=='update'?'编辑部门':handleType=='addsub'?'添加下级部门':'新增部门'"
      :visible.sync="visible"
      :before-close="handleClose"
    >
      <el-form label-width="80px" :model="handleForm" ref="handleForm" size="small" :rules="rules">
        <el-form-item label="部门名称" prop="organName" required>
          <el-input v-model.trim="handleForm.organName" show-word-limit maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="organCode" required>
          <el-input v-model.trim="handleForm.organCode" show-word-limit maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="上级部门" prop="parentCode">
          <el-select v-model="handleForm.parentCode" :disabled="handleType=='addsub'">
            <el-option
              v-for="item in organAll"
              :key="item.id"
              :label="item.organName"
              :value="item.organCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input type="textarea" :rows="4" v-model="handleForm.description" show-word-limit maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          type="primary"
          @click="submit"
        >{{handleType=='add'||handleType=='addsub'?'立即创建':'修改'}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  organAllList,
  organAdd,
  organUpdate,
  organDel
} from "api/seting/organization";
export default {
  data() {
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("部门编码不能为空"));
      }
      setTimeout(() => {
        var reg = /[\u4E00-\u9FA5]/g;
        if (reg.test(value)) {
          return callback(new Error("部门编码不能含有中文"));
        }
        callback();
      }, 300);
    };
    return {
      visible: false,
      handleType: "add",
      handleForm: {
        organName: "",
        organCode: "",
        parentCode: "0",
        description: ""
      },
      params: {
        organName: ""
      },
      list: [],
      organAll: [{
        id:null,
        organName:"无",
        organCode:"0"
      }],
      selectedRow: [],
      rules: {
        organName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          { max: 10, message: "部门名称不能超过10个字符", trigger: "blur" }
        ],
        organCode: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          { max: 30, message: "部门名称不能超过30个字符", trigger: "blur" },
          { validator: checkCode, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    // 获取列表
    loadData() {
      if (this.loading) return;
      this.loading = true;
      organAllList(this.params).then(res => {
        this.loading = false;
        this.organAll.push(...res.data);
        this.list = this.generateOptions(res.data);
        console.log(this.list);
      });
    },
    generateOptions(datas) {
      //生成树状数据
      var result = [];
      for (let data of datas) {
        if (data.parentCode == "0") {
          //判断是否为顶层节点
          data.children = this.getchilds(data.organCode, datas); //获取子节点
          result.push(data);
        }
      }
      return result;
    },
    getchilds(organCode, array) {
      let childs = new Array();
      for (let arr of array) {
        //循环获取子节点
        if (arr.parentCode == organCode) {
          childs.push(arr);
        }
      }
      for (let child of childs) {
        //获取子节点的子节点
        let childscopy = this.getchilds(child.organCode, array); //递归获取子节点
        if (childscopy.length > 0) {
          child.children = childscopy;
        }
      }
      return childs;
    },
    //刷新
    refresh() {
      this.loadData();
    },
    // table 复选选中行
    handleSelectionChange(val) {
      this.selectedRow = val;
    },
    batchDel() {
      var rows = this.selectedRow.map(o => o.id);
      this.del(rows);
    },
    singleDel(row) {
      this.del([row.id]);
    },
    // 关闭弹框
    handleClose(done) {
      this.visible = false;
      this.$refs.handleForm.resetFields();
    },
    del(ids) {
      if (ids.length == 0) return;
      this.$confirm("此操作将永久删除部门,是否继续?", "提示")
        .then(_ => {
          organDel(ids)
            .then(res => {
              this.loadData();
              this.$message.success("删除成功");
              this.$refs.organTable.clearSelection();
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        })
        .catch(_ => {});
    },
    //提交
    submit() {
      this.$refs.handleForm.validate(valid => {
        if (valid) {
          let request =
            this.handleType == "add" || this.handleType == "addsub"
              ? organAdd
              : organUpdate;
          request(this.handleForm)
            .then(res => {
              this.visible = false;
              this.$message.success("操作成功");
              this.refresh();
              this.$refs.handleForm.resetFields();
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        } else {
          console.log("error submit!!");
        }
      });
    },
    //修改
    update(row) {
      this.visible = true;
      this.handleType = "update";
      this.$nextTick(() => {
        this.handleForm = Object.assign({}, row);
      });
    },
    //添加下级部门
    addsub(row) {
      this.visible = true;
      this.handleType = "addsub";
      this.$nextTick(() => {
        this.handleForm.parentCode = row.organCode;
      });
    }
  }
};
</script>

<style scoped lang="scss">
.filter-wrap {
  .el-input,
  .el-date-editor {
    width: 75%;
    min-width: 215px;
  }
}
</style>
